//
//  userAcount.swift
//  dwdWb
//
//  Created by Dengdwd on 15/10/7.
//  Copyright © 2015年 dwd. All rights reserved.
//

import UIKit

class UserAcount: NSObject,NSCoding {
    
    var access_token: String?
    var expires_data: NSDate?
    var expires_in: NSTimeInterval = 0 {
        didSet{
        expires_data = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    var uid: String?
    var name: String?
    var avatar_large: String?
    init(dict:[String:AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    override func setValue(value: AnyObject?, forUndefinedKey key: String) { }
    override var description : String {
        let keys = ["access_token","expires_data","uid","expires_in","name","avatar_large"]
    return "\(dictionaryWithValuesForKeys(keys))"
    }

    static let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("acount.plist")
    class func loadUserData () ->UserAcount? {
        if let acount = NSKeyedUnarchiver.unarchiveObjectWithFile(UserAcount.path) as? UserAcount{
            if acount.expires_data?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
                return acount
            }
            }
        return nil
    }
    func saveUserData() {
    NSKeyedArchiver.archiveRootObject(self, toFile: UserAcount.path)
//    print(UserAcount.path)
    }
    
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(expires_data, forKey: "expires_data")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
        
    }
    required init?(coder aDecoder: NSCoder) {
    access_token = aDecoder.decodeObjectForKey("access_token") as? String
    uid = aDecoder.decodeObjectForKey("uid") as? String
    expires_data = aDecoder.decodeObjectForKey("expires_data") as? NSDate
    name = aDecoder.decodeObjectForKey("name") as? String
    avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
    }
    func loadUserInfo(completion:(error:NSError?) ->()) {
    NetworkTools.sharedTools.loadUserInfo(access_token!, uid: uid!) { (dict, error) -> () in
        if error != nil {
        completion(error: error)
            return
        }
        self.name = dict!["name"] as? String
        self.avatar_large = dict!["avatar_large"] as? String
        self.saveUserData()
        completion(error: nil)
        }
    }
}
